package org.ph.share.lock.test.thread;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * Thread 测试类
 * 优雅的停止线程,禁止使用stop(),system.exit()
 *
 * @author Hush.
 * @since 2023/5/15 9:53
 */
@Slf4j
public class ThreadTest4 {
    public static void main(String[] args) throws InterruptedException {
        Monitoring monitoring = new Monitoring();
        // 开启状态监控
        monitoring.start();
        TimeUnit.SECONDS.sleep(5);
        // 模拟状态监控线程被打断
        monitoring.stop();
    }

    /**
     * 健康监控
     *
     * @author Hush.
     * @since 2023/5/16 15:08
     */
    static class Monitoring {
        private Thread thread;

        public void start() {
            thread = new Thread("monitoring - 1") {
                @Override
                public void run() {
                    while (true) {
                        Thread thread1 = Thread.currentThread();
                        // Thread.interrupted()
                        if (thread1.isInterrupted()) {
                            log.warn("Interrupted！！！！！");
                            break;
                        }
                        try {
                            TimeUnit.SECONDS.sleep(1);
                            log.info("健康状态 100%");

                        } catch (InterruptedException e) {
                            log.info("thread1.isInterrupted():{}",thread1.isInterrupted());
                            // 这里捕获到InterruptedException,会清除打断的标记,所以这里需要重新调用interrupt()
                            thread1.interrupt();
                            // throw new RuntimeException(e);
                        }
                    }
                }
            };
            thread.start();
        }

        public void stop() {
            thread.interrupt();
        }
    }
}
